/* 核心调用类 */
class MultiChannels {
  constructor(token) {
    let that = this;
    this.token = this.getUrlParam('token') || token;
    this.websocketServe = null
    this.init();
		//读取config.ini配置文件的ip
    this.readTextFile("js/config.ini", function (res) {
      that.baseConfig = res;
      console.log("初始化成功，获取ini配置文件数据", res);
    });
    // this.getJsIp()
  }
  getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }

  // 简单封装请求
  ajax(obj) {
    let that = this;
    // 默认参数
    var defaults = {
      type: "get",
      data: {},
      url: "#",
      dataType: "json",
      async: true,
      success: function (data) {
        console.log(data);
      }
    };
    // 处理形参，传递参数的时候就覆盖默认参数，不传递就使用默认参数
    for (var key in obj) {
      //把输入的参数与设置的默认数据进行覆盖更新
      defaults[key] = obj[key];
    }

    obj.async === false ? (defaults.async = false) : (defaults.async = true);
    // 1、创建XMLHttpRequest对象
    var xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    } else {
      xhr = new ActiveXObject("Microsoft.XMLHTTP"); // 兼容ie的早期版本
    }

    // 把对象形式的参数转化为字符串形式的参数
    /* {username:'zhangsan','password':123} 转换为 username=zhangsan&password=123 */
    var param = "";
    for (var attr in obj.data) {
      param += attr + "=" + obj.data[attr] + "&";
    }
    if (param) {
      //substring(start, end)截取字符串去掉最后的&符号
      param = param.substring(0, param.length - 1);
    }

    // 处理get请求参数并且处理中文乱码问题
    if (defaults.type == "get") {
      if (param && param.length > 0) {
        defaults.url += "?" + encodeURI(param);
      }
    }
    // 2、准备发送（设置发送的参数）
    xhr.open(defaults.type, defaults.url, defaults.async); // 处理post请求参数并且设置请求头信息（必须设置）
    var data = null;
    if (this.token) {
      xhr.setRequestHeader("token", this.token);
    }

    if (defaults.type == "post") {
      data = JSON.stringify(obj.data);
      xhr.setRequestHeader("Content-Type", "application/json");
      // xhr.setRequestHeader("Access-Control-Allow-Origin","*")
      //post模式下必须加的请求头，这个请求头是告诉服务器怎么去解析请求的正文部分。
    }
    // 4、指定回调函数（处理服务器响应数据）
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        //4 获取数据成功
        if (xhr.status == 200) {
          //200 获取的数据格式正确
          var data = xhr.responseText;
          if (defaults.dataType == "json") {
            data = JSON.parse(data);
          }
          defaults.success.call(that, data);
        }
      }
    };
    // 3、执行发送动作
    xhr.send(data);
    // 处理同步请求，不会调用回调函数
    /*if (!defaults.async) {
      if (defaults.dataType == 'json') {
        return JSON.parse(xhr.responseText);
      } else {
        return xhr.responseText;
      }
    }*/
  }

  readTextFile(file, callback) {
    var that = this;
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
      if (rawFile.readyState === 4 && rawFile.status == "200") {
        callback(that.ParseINIString(rawFile.responseText));
      }
    };
    rawFile.send(null);
  }
  // 进行Ini文件内容的解析，解析成Json格式
  ParseINIString(data) {
    //利用正则表达式进行ini文件每行数据的匹配
    var regex = {
      section: /^\s*\s*([^\s*([^]*)\s*\]\s*$/,
      param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
      comment: /^\s*;.*$/
    };
    var JsonValue = {};
    var lines = new Array();
    lines = data.split(/\r\n|\r|\n/);
    //将字符串进行根据回车拆分为字符串数组
    var section = null;
    //对字符串数组进行正则表达式匹配，来组装Json对象
    var iArraySize = lines.length;
    for (var i = 0; i < iArraySize; ++i) {
      let line = lines[i];
      if (regex.comment.test(line)) {
        //如果为注释的话，不进行操作
      } else if (regex.param.test(line)) {
        var match = line.match(regex.param);
        if (section) {
          JsonValue[section][match[1]] = match[2];
        } else {
          JsonValue[match[1]] = match[2];
        }
      } else if (regex.section.test(line)) {
        var match = line.match(regex.section);
        JsonValue[match[1]] = {};
        section = match[1];
      } else if (line.length == 0 && section) {
        section = null;
      }
    }
    return JsonValue;
  }


  init() {
    window.eventBusfun = {
      eventTimer: null,
      eventList: [],
      emit(eventName, ...params) {
        console.log('emit', eventName)
        window.dispatchEvent(new CustomEvent(eventName, {
          detail: params
        }))
      },
      on(eventName, callBack) {
        window.addEventListener(eventName, ({ detail }) => {
          console.log('on', eventName, detail)
          callBack && callBack.apply(callBack, detail)
        })
      }
    };
  }


  init_back() {
    window.aiEvent = {
      off: function (eventName) {
        this[eventName] = []
        return this
      },
      on: function (eventName, callback) {
        console.log('on', eventName)
        if (!this[eventName]) {
          this[eventName] = [];
        }
        this[eventName].push(callback);
      },
      emit: function (eventName) {
        console.log('emit', eventName)
        var that = this;
        var params =
          arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : [];
        if (that[eventName]) {
          Array.prototype.forEach.call(that[eventName], function (arg) {
            arg.apply(self, params);
          });
        }
      }
    };
  }


  //坐席辅助连接websocket
  connInitOpenSdk(callId, sip, businessTypeId) {
    let that = this
    this.websocketServe = null
    let powerParam = {
      "mapNavigation":true,    //思路导航
      "knowledgeRecommend":true,   //知识推荐
      "infoExtract":true,          //信息提取
      "userPortrait":true,      //用户画像
      "callId":callId
    }
    //sdk鉴权
    this.getSdkPower(powerParam)

    //话术地图列表
    this.getMapList(businessTypeId)
    // 填单字段项
    this.getFillFormFun(businessTypeId)

    if ("WebSocket" in window) {
      this.websocketServe = new WebSocket(this.baseConfig.wsUrl + "/websocket/" + callId + "/" + sip + "/" + businessTypeId + '?token=' + this.token);
      let jsonData = {}

      this.websocketServe.onopen = function () {
        heartCheck.reset().start(callId);
        console.log("打开连接");
      }

      this.websocketServe.onmessage = function (event) {
        let strData = event.data;
        //获取进度
        if (strData.indexOf("progress:") == 0) {
          let progress = strData.substring(9, strData.length)
          window.eventBusfun.emit("progress", progress);
        }
        //调用相关消息  seat 坐席 , user 用户
        if (strData.indexOf("msg:") == 0) {
          //消息 msg
          let newData = strData.substring(4, strData.length);
          console.log("消息 newData=" + newData);
          jsonData = JSON.parse(newData);

          if (jsonData == null) {
            return;
          }
          window.eventBusfun.emit("assistCallResBackWS", jsonData);

        } else if (strData.indexOf("intent:") == 0) {
          //意图  intention
          let newData = strData.substring(7, strData.length);
          jsonData = JSON.parse(newData);
          if (jsonData[0].type == 'gold') {
            //获取 意图 数据
            window.eventBusfun.emit("intentionData", jsonData[0]);
          }
          if (jsonData[0].type == 'map') {
            //话术地图
            window.eventBusfun.emit("mapData", jsonData);
          }

        } else if (strData.indexOf("qualityTest:") == 0) {
          //质检（客服说错的内容）
          let newData = strData.substring(12, strData.length);
          console.log("质检 newData=" + newData);
          jsonData = JSON.parse(newData);
          if (jsonData == null) {
            return;
          }
          //获取 质检 数据
          window.eventBusfun.emit("qulityTestData", jsonData);
        } else if (strData.indexOf("fillForm:") == 0) {
          //自动填单
          let newData = strData.substring(9, strData.length);
          console.log("填单 newData=" + newData);
          jsonData = JSON.parse(newData);
          if (jsonData == null) {
            return;
          }
          window.eventBusfun.emit("callFillFormData", jsonData);
        } else if (strData.indexOf("changeProduct:") == 0) {
          let newData = strData.substring(14, strData.length)
          jsonData = JSON.parse(newData);
          if (jsonData == null) {
            return;
          }
          window.eventBusfun.emit("productMsg", jsonData);
          that.getMapList(jsonData.id)
          that.getFillFormFunAdd(jsonData.id)
        }
      }

      //连接发生错误的回调方法
      this.websocketServe.onerror = function (event) {
        console.log("WebSocket:发生错误");
        reconnect();
      };

      //连接关闭的回调方法
      this.websocketServe.onclose = function (event) {
        heartCheck.reset()
        console.log("WebSocket:已关闭");
      };

      /**
       * 坐席辅助===websocket心跳检测
       */
      var heartCheck = {
        timeout: 5000,
        timeoutObj: null,
        reset: function () {
          clearTimeout(this.timeoutObj);
          return this;
        },
        start: function (callId) {
          var self = this;
          this.timeoutObj && clearTimeout(this.timeoutObj);
          this.timeoutObj = setInterval(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            var heartBeat = { "cmd": "ping", "callId": callId };
            that.websocketServe ? that.websocketServe.send(JSON.stringify(heartBeat)) : "";
          }, this.timeout)

        }
      };

      this.resetWs = heartCheck.reset.bind(heartCheck);

    } else {
      alert("您的浏览器不支持WebSocket");
    }

  }

  closeWebsocketServe() {
    if (this.websocketServe) {
      this.websocketServe.close(1000);
    }
  }

  //对接sdk鉴权接口
  getSdkPower(param) {
    this.ajax({
      data: param,
      type: "post",
      url: this.baseConfig.httpUrl + "/sdk/stream/agentAuth",
      success: function (res) {
        if (res.flag) {

        } else {
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }

  // 点赞
  thumbsUp(businessTypeId, id, callId) {
    console.log(this.baseConfigUrl)
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/ok/" + businessTypeId + "/" + id + "/" + callId,
      success: function (res) {
        if (res.flag) {
          console.log("点赞成功！" || res.msg);
        } else {
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }
  //点踩
  thumbsDown(businessTypeId, id, callId) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/no/" + businessTypeId + "/" + id + "/" + callId,
      success: function (res) {
        if (res.flag) {
          console.log("点踩成功！" || res.msg);
        } else {
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }

  //获取自动填单字段项
  getFillFormFun(businessTypeId) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/queryFillFormFieldList/" + businessTypeId,
      success: function (res) {
        console.log(res)
        if (res.flag) {
          window.eventBusfun.emit("callFieldList", res.data);
        } else {
          console.log(res.msg || '获取字段项失败')
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }

  getFillFormFunAdd(businessTypeId) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/queryFillFormFieldList/" + businessTypeId,
      success: function (res) {
        console.log(res)
        if (res.flag) {
          window.eventBusfun.emit("newcallFieldList", res.data);
        } else {
          window.eventBusfun.emit("newcallFieldList", []);
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }

  //获取话术地图列表
  getMapList(businessTypeId) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/getMapList/" + businessTypeId,
      success: function (res) {
        console.log('话术地图列表', res)
        if (res.flag) {
          window.eventBusfun.emit("mapList", res.data);
        } else {
          window.eventBusfun.emit("mapList", []);
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }


  //获取话术地图的详情--开场指引话术
  getFirstMap(bussinessId, id) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/getFirstMap/" + bussinessId + "/" + id,
      dateType: 'json',
      success: function (res) {
        if (res.flag) {
          window.eventBusfun.emit("firstMapSpeech", res.data);
        } else {
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
          console.log(res.msg || '获取开场指引话术失败')
        }
      }
    });
  }

  //点击获取当前、下一节点
  getNodesFun(businessTypeId, flowId) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + "/agent/sdk/getFlowIntention/" + businessTypeId + "/" + flowId,
      success: function (res) {
        if (res.flag) {
          window.eventBusfun.emit("nodesData", res.data);
        } else {
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });
  }

  // 知识搜索
  getSearchKnowledge(busId, searchkey) {
    this.ajax({
      type: "get",
      url: this.baseConfig.httpUrl + '/agent/sdk/getSearchKnowledgesAction/' + busId + '?searchKey=' + searchkey,
      success: function (res) {
        if (res.flag) {
          window.eventBusfun.emit("knowledgeData", res.data.records);
        } else {
          window.eventBusfun.emit("errorEvent", {
            code: res.data ? res.data.code : '',
            data: res.msg
          })
        }
      }
    });

  }

  //坐席文本发消息
  seatSend(param) {
    this.ajax({
      data: param,
      type: "post",
      url: this.baseConfig.httpUrl + "/agent/sdk/sendTextHandler",
      success: function (res) {
        if (res.flag) {
          console.log(res);
        } else {
          console.log(res.msg)
        }
      }
    });
  }

  //客户文本发消息
  cusSend(param) {
    this.ajax({
      data: param,
      type: "post",
      url: this.baseConfig.httpUrl + "/agent/sdk/sendTextHandler",
      success: function (res) {
        if (res.flag) {
          console.log(res);
        } else {
          console.log(res.msg)
        }
      }
    });
  }

}
window.MultiChannel = MultiChannels;

//坐席辅助重连操作
var lockReconnect = false, tt;
function reconnect() {
  if (lockReconnect) {
    return;
  }
  lockReconnect = true;
  tt && clearTimeout(tt);
  tt = setTimeout(function () {
    console.log('重连中...');
    lockReconnect = false;
  }, 4000);
}
